<template>
   <div class="pageWrapper">
    <SearchBar @onSearch="handleSearch" @childFn="resetFormSearch">
      <SearchBarItem label="机构编码：" :labelLg="8">
        <Input type="text" v-model="searchDataModule.organizationCode" placeholder="请输入机构编码" clearable />
      </SearchBarItem>
      <SearchBarItem label="机构名称：" :labelLg="8">
        <Input type="text" v-model="searchDataModule.organizationName" placeholder="请输入机构名称" clearable />
      </SearchBarItem>
    </SearchBar>
    <RemoteTable :namespace="namespace" :columns="columns" @onSortChange="onSortChange">
      <template #extra>
        <Authc permissions="trade:merchant:institutional:edit">
          <Button type="primary" @click="handleClick('add')">新增</Button>
        </Authc>
        <Authc permissions="trade:merchant:institutional:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>
    </RemoteTable>

    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="title">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">
          <FormItem label="机构编码：" >
            <Input type="text" v-if="!showCode" v-model.trim="dataModule.organizationCode" :maxlength="maxlength" placeholder="请填写,长度不超多32" clearable/>
            <div v-else>{{dataModule.organizationCode}}</div>
          </FormItem>
          <FormItem prop="organizationName" label="机构名称：">
            <Input type="text" v-model.trim="dataModule.organizationName" :maxlength="maxlength" placeholder="请填写,长度不超多32" clearable/>
          </FormItem>
          <FormItem label="备注：">
            <Input type="textarea" v-model="dataModule.remark" placeholder="请填写" show-word-limit maxlength="200" clearable/>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">取消</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card
} from "view-design";
import Loading from "@/components/Loading";
import RemoteTable from "@/components/RemoteTable";
import RemoteSelect from "@/components/RemoteSelect";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../module/institutional";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";
import util from "@/utils/util";

export default {
  name: 'tables_page',
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card
  },
  data () {
    return {
      maxlength: 32,
      title: '',
      isShow: false,
      showCode: true,
      namespace: namespace,
      loading: true,
      searchDataModule: {},
      dataModule: {},
      tableData: [],
      ruleValidate: {
        organizationName: [{ required: true, message: '机构名称不能为空', trigger: 'blur' }]
      },
      columns: [
        {
          title: '序号',
          type: 'index',
          width: 80,
          align: 'center'
          // fixed: 'left'
        },
        {
          title: '机构编码',
          key: 'organizationCode',
          minWidth: 150,
          align: 'center'
          // fixed: 'left'
        },
        {
          title: '机构名称',
          key: 'organizationName',
          minWidth: 150,
          align: 'center'
        },
        // {
        //   title: '已开通业务',
        //   key: 'business',
        //   minWidth: 250,
        //   align: 'center',
        //   render: (h, params) => {
        //     return h('div', [
        //       h('Button', {
        //         props: {
        //           type: 'primary',
        //           size: 'small'
        //         },
        //         style: {
        //           marginRight: '5px'
        //         },
        //         on: {
        //           click: () => {
        //             this.openBusinessModel(params.row)
        //           }
        //         }
        //       }, '修改'),

        //     ])
        //   }
        // },
        {
          title: '备注',
          key: 'remark',
          minWidth: 150,
          align: 'center'
        },
        {
          title: "操作",
          key: "action",
          width: 100,
          // fixed: "right",
          align: "center",
          permissions: ["trade:merchant:manager"],
          width: 200,
          render: function(h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      addtype: true
    }
  },
  created () {
    /** 如果 url 没有带参数，就重置请求参数 **/
    this.$store.commit(`${namespace}/reviseQuery`);
  },
  methods: {
    // 导出
    async exportExcel () {
      try {
        let res = await this.$store.dispatch(`${namespace}/exportExcel`, this.searchDataModule);
        let link = document.createElement('a');

        util.exportExcle(res, '组织机构管理表');
      } catch (error) {
         this.$Message.error({
          content: '导出失败'
        })
      }
    },
    // 清空事件；
    resetFormSearch() {
      this.$set(this.searchDataModule, 'organizationCode', '')
      this.$set(this.searchDataModule, 'organizationName', '')
    },
    handleSubmitCancel (formName) {
      this.isShow = false
      this.$refs[formName].resetFields()
    },
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.addtype) {
            this.$store.dispatch(`${namespace}/save`, this.dataModule).then(res => {
              if (res.errorCode === 0) {
                this.$Message.success({
                  content: res.msg
                });
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.warning({
                  content: res.msg
                })
              }
            })
          } else {
            this.$store.dispatch(`${namespace}/localUpdate`, this.dataModule).then(res => {
              if (res.errorCode === 0) {
                this.$Message.success({
                  content: res.msg
                });
                this.$store.dispatch(`${namespace}/query`);
              }
            })
          }
          this.isShow = false;
        } else {
          console.log('error submit!!')
          // return false
        }
      })
    },
    // 重置
    resetForm() {
       if(this.$refs['dataModule'].fields){
        this.$refs['dataModule'].fields.forEach(function (e) {
            if (e.prop == 'organizationName') e.resetField();
          })
       }
    },
    handleClick(type) {
      this.resetForm();
      this.addtype = true
      switch (type) {
        case 'add':
          this.showCode = false
          this.isShow = true
          this.title = '新增机构信息';
          this.dataModule = {}
          break
        case 'edit':

          break
        case 'delete':

          break
        default:
      }
    },
    handleSearch() {
      let pageSize = {
        currentPage: 1,
        pageSize: 10
      }
      this.$store.dispatch(`${namespace}/query`, { ...this.searchDataModule, ...pageSize });
    },
    onSortChange(sort) {
      if (sort.order === "normal") {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + " " + sort.order];
      }
      this.handleSearch();
    },
    // resetForm() {
      //   this.$refs["formArea"].resetFields();
    // }
  },
  beforeDestroy() {
    this.$bus.$off('actionType');
  },
  async mounted() {
    this.$bus.$on('actionType', (data) => {
      let id = data.id
        if (data.type === 'edit') {
          this.resetForm();
          this.title = '编辑机构信息'
          this.isShow = true
          this.showCode = true
          this.addtype = false
          this.$store.dispatch(`${namespace}/getDetail`, id).then(res => {
            this.dataModule = res.data
          });

        } else if (data.type === 'delete') {
          Modal.confirm({
            render: (h, params) => {
              return h('div', [
                h('div', {
                  style:"margin-bottom:10px;vertical-align: middle;font-size: 16px;color: #17233d;font-weight: 700;"
                }, '提示'),
                h('div', {
                  class: 'selfConfirm'
                }, '是否确认删除?')
              ]);
            },
            onOk: () => {
              return this.$store.dispatch(`${namespace}/delete`, id).then(res => {
                if (res.ret === 0) {
                  this.$Message.success({
                    content: res.msg
                  });
                  this.$store.dispatch(`${namespace}/query`);
                } else {
                  this.$Message.warning({
                    content: res.msg
                  })
                }
              })
            }
          })
        }
      });
  }
}
</script>
